import { useMemo, useState, useEffect } from 'react';

interface UseVirtualListOptions {
  itemHeight: number;
  containerHeight: number;
  overscan?: number;
}

export function useVirtualList<T>(
  list: T[],
  options: UseVirtualListOptions
) {
  const { itemHeight, containerHeight, overscan = 5 } = options;
  const [scrollTop, setScrollTop] = useState(0);

  const visibleItems = useMemo(() => {
    const visibleCount = Math.ceil(containerHeight / itemHeight);
    const startIndex = Math.floor(scrollTop / itemHeight);
    const endIndex = Math.min(startIndex + visibleCount + overscan, list.length);
    const actualStartIndex = Math.max(0, startIndex - overscan);

    return {
      items: list.slice(actualStartIndex, endIndex).map((item, index) => ({
        data: item,
        index: actualStartIndex + index
      })),
      startIndex: actualStartIndex,
      endIndex,
      totalHeight: list.length * itemHeight,
      offsetY: actualStartIndex * itemHeight
    };
  }, [list, scrollTop, itemHeight, overscan, containerHeight]);

  const scrollElementProps = {
    style: {
      height: containerHeight,
      overflowY: 'auto' as const,
    },
    onScroll: (e: React.UIEvent<HTMLDivElement>) => {
      setScrollTop(e.currentTarget.scrollTop);
    }
  };

  return {
    list: visibleItems,
    scrollElementProps
  };
}